package interfaces.subpanel.preprocesamiento.gui;

import java.awt.BorderLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.apache.commons.lang3.StringUtils;

import utils.ImagenesUtils;

public class StopWordsPanelGUI extends JPanel implements ActionListener {

	private static final long serialVersionUID = 1L;

	static private final String newline = "\n";

	private JTextArea stopWordsArea;

	private JButton addStopWordButton;

	private JTextField newStopWordLabel;

	private String pathToStopWordFile = "/englishStopWords.txt";

	private boolean interactWithFile;

	public StopWordsPanelGUI(boolean interactWithFile, boolean showDescription) {

		super(new BorderLayout(5, 5));

		this.interactWithFile = interactWithFile;

		JPanel topPanel = new JPanel(new BorderLayout(5, 5));

		JPanel descriptionPanel = new JPanel(new BorderLayout(10, 3));
		JTextArea descriptionText = new JTextArea(
				"Stop words are those words which are so common that they are useless to index or use in search engines or other search indexes. "
						+ "Usually articles, adverbials or adpositions are stop words. For this reason, they are filtered before the classification starts.\n");
		descriptionText.setLineWrap(true);
		descriptionText.setWrapStyleWord(true);
		descriptionText.setEditable(false);
		descriptionText.setColumns(20);
		descriptionText.setBackground(null);
		descriptionPanel.add(descriptionText, BorderLayout.CENTER);

		JPanel addStopWordPanel = new JPanel(new BorderLayout(5, 1));
		this.newStopWordLabel = new JTextField();
		this.addStopWordButton = new JButton("", ImagenesUtils.createImageIcon(this.getClass(), "/add.png"));
		this.addStopWordButton.setSize(30, 30);
		this.addStopWordButton.addActionListener(this);
		addStopWordPanel.add(this.newStopWordLabel, BorderLayout.CENTER);
		addStopWordPanel.add(this.addStopWordButton, BorderLayout.EAST);

		if (showDescription)
			topPanel.add(descriptionPanel, BorderLayout.NORTH);
		topPanel.add(addStopWordPanel, BorderLayout.CENTER);

		this.stopWordsArea = new JTextArea();
		this.stopWordsArea.setLineWrap(true);
		this.stopWordsArea.setWrapStyleWord(true);
		this.stopWordsArea.setEditable(true);
		this.stopWordsArea.setColumns(20);
		this.stopWordsArea.setMargin(new Insets(3, 3, 3, 3));
		if (this.interactWithFile)
			this.stopWordsArea.setText(loadStopWordsFileIntoTextArea());
		this.stopWordsArea.setCaretPosition(0);

		JScrollPane stopWordsPane = new JScrollPane(this.stopWordsArea);

		this.setBorder(BorderFactory.createCompoundBorder(
				BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Stop-words List: "), BorderFactory.createEmptyBorder(5, 5, 5, 5)),
				this.getBorder()));

		add(topPanel, BorderLayout.NORTH);
		add(stopWordsPane, BorderLayout.CENTER);
	}

	private String loadStopWordsFileIntoTextArea() {

		StringBuilder contents = new StringBuilder();
		try {

			InputStream is = getClass().getResourceAsStream(this.pathToStopWordFile);
			BufferedReader input = new BufferedReader(new InputStreamReader(is));
			String line = null;
			try {
				while ((line = input.readLine()) != null) {
					contents.append(line + newline);
				}
			} finally {
				input.close();
			}
		} catch (FileNotFoundException e) {
			JOptionPane.showMessageDialog(this, "Stop Words File not found.", "File not found!", JOptionPane.ERROR_MESSAGE,
					ImagenesUtils.createImageIcon(this.getClass(), "/stop.png"));
		} catch (IOException e) {
			JOptionPane.showMessageDialog(this, "Couldn't read Stop Words File.", "Read file Error!", JOptionPane.ERROR_MESSAGE,
					ImagenesUtils.createImageIcon(this.getClass(), "/stop.png"));
		}

		return contents.toString();
	}

	private void writeNewStopWordToFile() {

		File stopWordsFile = new File(getClass().getResource(pathToStopWordFile).getFile());

		if (!stopWordsFile.exists()) {
			JOptionPane.showMessageDialog(this, "File does not exist: " + stopWordsFile, "Error", JOptionPane.ERROR_MESSAGE,
					ImagenesUtils.createImageIcon(this.getClass(), "/stop.png"));
		}
		if (!stopWordsFile.canWrite()) {
			JOptionPane.showMessageDialog(this, "File cannot be written: " + stopWordsFile, "Error", JOptionPane.ERROR_MESSAGE,
					ImagenesUtils.createImageIcon(this.getClass(), "/stop.png"));
		}

		try {
			Writer output = null;
			try {
				output = new BufferedWriter(new FileWriter(stopWordsFile));
				output.write(this.stopWordsArea.getText());
			} finally {
				this.newStopWordLabel.setText("");
				output.flush();
				output.close();
			}
		} catch (Exception e) {
			JOptionPane
					.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE, ImagenesUtils.createImageIcon(this.getClass(), "/stop.png"));
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		if (e.getSource() == this.addStopWordButton) {

			if (StringUtils.isNotBlank(this.newStopWordLabel.getText())) {
				this.stopWordsArea.append(this.newStopWordLabel.getText() + newline);
				this.newStopWordLabel.setText("");
				if (this.interactWithFile)
					writeNewStopWordToFile();
			} else
				JOptionPane.showMessageDialog(this, "You must enter a new Stop Word in the field to be added to the list.", "No new Stop Word Error!",
						JOptionPane.ERROR_MESSAGE, ImagenesUtils.createImageIcon(this.getClass(), "/stop.png"));
		}
	}

	public JTextArea getStopWordsArea() {
		return stopWordsArea;
	}

}
